package org.dtrd.modules.shop.controller;


import org.dtrd.common.util.StringUtil;
import org.dtrd.config.common.PathUtil;
import org.dtrd.config.pay.PayConstant;
import org.dtrd.config.system.Constant;
import org.dtrd.config.wechat.api.impl.WechatApi;
import org.dtrd.config.wechat.entity.bean.officialaccount.template.OrderDeliveryMsg;
import org.dtrd.config.wechat.entity.bean.officialaccount.template.OrderStateMsg;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.shop.entity.bean.*;
import org.dtrd.modules.shop.entity.po.DtrdEntShcRdOrder;
import org.dtrd.modules.shop.entity.po.DtrdEntShcRdOrderJoinAddress;
import org.dtrd.modules.shop.service.IDtrdEntShcRdOrderJoinAddressService;
import org.dtrd.modules.shop.service.IDtrdEntShcRdOrderRefundService;
import org.dtrd.modules.shop.service.IDtrdEntShcRdPatientAddressService;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.dtrd.common.aspect.annotation.AutoLog;
import org.dtrd.modules.shop.service.IDtrdEntShcRdOrderService;
import org.dtrd.common.api.vo.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;
import org.dtrd.base.BaseController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.List;
import java.util.Optional;

import static org.dtrd.common.constant.CommonConstant.*;
import static org.dtrd.config.system.SystemState.ResponseState.*;

/**
 * <p>
 * 订单记录表 前端控制器
 * </p>
 * @author sun
 * @since 2022-07-23
 */
@Api(tags = "商城")
@RestController
@RequestMapping("/shop")
public class DtrdEntShcRdOrderController extends BaseController {

    @Autowired
    private IDtrdEntShcRdOrderService orderService;

    @Autowired
    private IDtrdEntShcRdPatientAddressService patientAddressService;

    @Autowired
    private IDtrdEntShcRdOrderRefundService orderRefundService;

    @Autowired
    private IDtrdEntShcRdOrderJoinAddressService orderJoinAddressService;

    @Autowired
    private IDtrdEntRdPatientService patientService;

    @Autowired
    @Lazy
    private WechatApi wechatApi;

    @ApiOperation(value = "获取我的收货地址", response = PatientAddressListInfo.class)
    @PostMapping("/address")
    @AutoLog(value="查询列表", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getMyAddress(@RequestBody PatientAddressListRequest request){
        List<PatientAddressListInfo> page = patientAddressService.getPatientAddressList(request);
        return Result.OK(page);
    }

    @ApiOperation(value = "新增或编辑我的收货地址")
    @PostMapping("/address/save")
    public Result<?> saveOrUpdateMyAddress(@RequestBody @Validated PatientAddressDetail dto){

        boolean result = patientAddressService.saveOrUpdatePatientAddress(dto);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation(value = "删除我的收货地址")
    @DeleteMapping("/address/delete")
    public Result<?> deleteMyAddress(@RequestParam Integer dataId){

        boolean result = patientAddressService.removePatientAddress(dataId);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation(value = "设为默认地址")
    @PostMapping("/address/default")
    public Result<?> setDefaultAddress(@RequestBody @Validated PatientAddressSetDefaultRequest request){

        boolean result = patientAddressService.setDefaultAddress(request);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation(value = "获取我的订单")
    @PostMapping("/orders")
    public Result<?> getMyOrders(@RequestBody @Validated OrderListRequest request){

        List<OrderListInfo> orderList = orderService.getOrderList(request);
        return Result.OK(orderList);
    }

    @ApiOperation(value = "发起退款")
    @PostMapping("/order/refund")
    public Result<?> createOrderRefund(@RequestBody OrderRefundDetail request){

        return  orderRefundService.saveOrUpdateOrderRefund(request);
    }


    @ApiOperation(value = "分页查询订单列表", response = OrderListInfo.class)
    @PostMapping("/order/oms")
    @AutoLog(value="查询列表", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getOrderList(@RequestBody @Validated OrderOmsPageRequest request){
        handlePageRequest(request);
        IPage<OrderListInfo> page = orderService.omsPageOrder(request);
        return Result.OK(page);
    }

    @ApiOperation(value = "发货信息", response = OrderJoinAddressDetail.class)
    @GetMapping("/order/logistics")
    @AutoLog(value="查询列表", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getOrderLogisticsAddress(@RequestParam @Validated String orderId){
        if (orderId.equals("")) {
            return Result.error("参数错误");
        }
        OrderJoinAddressDetail orderJoinAddressDetail = orderJoinAddressService.getOrderJoinAddressByOrderId(orderId);
        return Result.OK(orderJoinAddressDetail);
    }

    @ApiOperation(value = "保存物流信息")
    @PostMapping("/order/logistics/save")
    @AutoLog(value="查询列表", operateType = OPERATE_TYPE_QUERY)
    public Result<?> saveOrderLogisticsAddress(@RequestBody @Validated OrderJoinAddressDetail orderJoinAddressDetail){
        DtrdEntShcRdOrder orderDetail = orderService.getById(orderJoinAddressDetail.getOrderId());
        if (orderDetail == null) {
            Result.error("数据异常");
        }
        boolean save = orderJoinAddressService.saveOrUpdateOrderJoinAddress(orderJoinAddressDetail);
        if (save) {
            // 修改订单状态
            orderDetail.setOrderInfoOrderstatus(PayConstant.OrderStatus.IS_DELIVERY.getType());
            boolean updateOrder = orderService.updateById(orderDetail);
            if (updateOrder) {
                Integer patientId = orderDetail.getOrderInfoUserid();
                String openid = Optional.ofNullable(patientId).map(id -> patientService.getById(id)).map(DtrdEntRdPatient::getWxOaOpenid).orElse(null);
                if (openid != null) {
                    OrderDeliveryMsg orderDeliveryMsg = OrderDeliveryMsg.OrderDeliveryMsgBuilder.getInstance()
                            .buildOrderPsySuccessMsg(("您购买的"+orderDetail.getOrderInfoTitle()+"已发货"),
                                    orderJoinAddressDetail.getContactPerson(),
                                    orderJoinAddressDetail.getContactPhone(),
                                    orderJoinAddressDetail.getLogisticsName(),
                                    orderJoinAddressDetail.getLogisticsNo(),
                                    "请保持手机畅通，以便快递及时联系您").build();
                    wechatApi.sendOrderDeliveryMsg(orderDeliveryMsg, openid);
                }
            }
            return updateOrder ? Result.OK() : Result.error("操作失败");
        } else {
            return Result.error("操作失败");
        }
    }

    @ApiOperation(value = "发货信息", response = OrderRefundDetail.class)
    @GetMapping("/order/refund/detail")
    @AutoLog(value="查询列表", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getOrderRefund(@RequestParam @Validated String orderId){
        if (orderId.equals("")) {
            return Result.error("参数错误");
        }
        OrderRefundDetail orderRefundDetail = orderRefundService.getOrderRefundByOrderId(orderId);
        return Result.OK(orderRefundDetail);
    }

    @ApiOperation(value = "退款订单审核")
    @PostMapping("/order/refund/verify")
    @AutoLog(value="退款订单审核", operateType = OPERATE_TYPE_QUERY)
    public Result<?> refundOrderVerify(@RequestBody @Validated OrderRefundVerifyRequest verifyRequest){

        boolean update = orderRefundService.orderRefundVerify(verifyRequest);
        return update ? Result.OK() : Result.error("审核失败");
    }
}
